package com.saxon.shiro.controller;

import com.saxon.shiro.pojo.Teacher;
import com.saxon.shiro.service.TeacherService;
import com.saxon.shiro.service.TeacherServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;


@RestController
@Api ("自定义的视图解析")
public class mycontroller {

    TeacherService teacherService;

    @Autowired
    public void setTeacherService (TeacherService
                                               teacherService) {
        this.teacherService = teacherService;
    }

    @GetMapping ( {"/", "/index"})
    @ApiOperation ("登录视图")
    public String index () {
        return "index";
    }

    @GetMapping ("/test/1")
    public String test () {
        return "/test/1";
    }

    @GetMapping ("/tologin")
    public String tologin () {
        return "/login";
    }

    @ApiOperation ("登录验证")
    @GetMapping ("/login")
    public String login (String username, String password, Model model) {
        Subject subject = SecurityUtils.getSubject ();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken (username, password);
        try {
            subject.login (usernamePasswordToken);
            return "/index";
        } catch (UnknownAccountException e) {
            model.addAttribute ("msg", "用户错误");
            return "/login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute ("msg", "密码错误");
            return "/login";
        }

    }

    @GetMapping ("/getTeacher/{id},{name}")
    @ResponseBody
    public Teacher getTeacher (Teacher teacher, @PathVariable ("id") int id, @PathVariable ("name") String name) {

        return teacher;
    }


    @GetMapping ("/404")
    public String error () {
        return "/error";
    }

    @Scheduled(cron = "0/2 * * * * ?")
    @GetMapping ("/hello")
    @ResponseBody
    public String hello () {
        System.out.println ("successful");
        System.out.println ("在这里");
        teacherService.Asyn ();
        return "OK";
    }

}
